#!/bin/env python

import cv2

windowName = "fact_detector"

new_operate1 = 11
new_operate2 = 3

old_operate1 = 0
old_operate2 = 0

def trackbarCallback(value):
    pass

def detector_face(gray_img):
    # 使用级联分类器(级联检测器) 加载人脸特征
    fact_detector_data = cv2.CascadeClassifier("../../resource/data/haarcascade_frontalface_alt.xml")
    # 检测人脸，输出坐标，x,y,w,h
    face_pos = fact_detector_data.detectMultiScale(gray_img, scaleFactor = new_operate1 / 10, minNeighbors = new_operate2)

    return face_pos

if __name__ == '__main__':
    raw_img = cv2.imread("../../resource/pic/heying2.jpg")
    if raw_img is None:
        print("resource not exist")
        exit(-1)
    gray_img = cv2.cvtColor(raw_img, cv2.COLOR_BGR2GRAY)

    cv2.namedWindow(windowName, cv2.WINDOW_NORMAL)
    cv2.createTrackbar('scaleFactor', windowName, new_operate1, 100, trackbarCallback)
    cv2.createTrackbar('minNeighbors', windowName, new_operate2, 30, trackbarCallback)
    cv2.setTrackbarMin('scaleFactor', windowName, 11)
    cv2.setTrackbarMin('minNeighbors', windowName, 1)

    while True:
        new_operate1 = cv2.getTrackbarPos('scaleFactor', windowName)
        new_operate2 = cv2.getTrackbarPos('minNeighbors', windowName)

        if old_operate1 != new_operate1:
            print("scaleFactor:", new_operate1)
            old_operate1 = new_operate1
            update_flag = 1

        if old_operate2 != new_operate2:
            print("minNeighbors:", new_operate2)
            old_operate2 = new_operate2
            update_flag = 1

        if update_flag == 1:
            update_flag = 0
            face_pos = detector_face(gray_img)
            out_img = raw_img.copy()
            if len(face_pos) != 0:
                for x,y,w,h in face_pos:
                    cv2.rectangle(out_img, (x, y), (x + w, y + h), (0, 255, 0), thickness=2)
                face_num = face_pos.shape[0]
            else:
                face_num = 0
            cv2.putText(out_img, str(face_num), (10, 30), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255))
            cv2.imshow(windowName, out_img)

        if cv2.waitKey(10) == ord('q'):
            break

    print('销毁窗口')
    cv2.destroyAllWindows()
